JavaScript30第二十二天要做的事情是文字聚光燈,當使用者從一個 DOM 元素移動到另外一個身上時,需要出現一個白色的光跑過去的特效
Github 檔案位置:22:Follow Along Link Highliter
網站初始的樣子
可以先玩玩 最後的成品
首先先讓我們做出聚光燈,並選取好會觸發聚光燈的 a 標籤,再幫他們通通加上 mouseenter 事件的監聽
const triggers = document.querySelectorAll('a');
// 選取所有的 a 元素
const highlight = document.createElement('span');
// 創造一個做聚光燈的 span 元素
highlight.classList.add('highlight');
// 加上寫好的 CSS 特效
document.body.appendChild(highlight);
// 將創造的元素放入 body 顯示在網頁上
triggers.forEach(a => a.addEventListener('mouseenter', highlightLink));
接下來是 function 的部分ㄌ,今天學習到了 getBoundingClientRect() 這個方法,他會回傳一個 DOMRect 物件,裡面可以取得座標、長、寬等等元素資訊
function highlightLink() {
  const linkCoords = this.getBoundingClientRect();
  console.log(linkCoords);
  const coords = {
    width: linkCoords.width,
    height: linkCoords.height,
    top: linkCoords.top + window.scrollY,
    left: linkCoords.left + window.scrollX
  };
}
接下來就只需要把元素的座標及大小賦值給剛創造的 span 聚光燈即可
備註:由於取得的 x, y 座標是相對可視範圍的座標,以可視範圍的左上角為起點,因此要再各自加上滾動軸的 x, y 值,才可以正常顯示
function highlightLink() {
  //...
  highlight.style.width = `${coords.width}px`;
  highlight.style.height = `${coords.height}px`;
  highlight.style.transform = `translate(${coords.left}px, ${coords.top}px)`;
}
    const triggers = document.querySelectorAll('a');
    // 選取所有的 a 元素
    const highlight = document.createElement('span');
    // 創造一個做聚光燈的 span 元素
    highlight.classList.add('highlight');
    // 加上寫好的 CSS 特效
    document.body.appendChild(highlight);
    // 將創造的元素放入 body 顯示在網頁上
    function highlightLink() {
      const linkCoords = this.getBoundingClientRect();
      console.log(linkCoords);
      const coords = {
        width: linkCoords.width,
        height: linkCoords.height,
        top: linkCoords.top + window.scrollY,
        left: linkCoords.left + window.scrollX
      };
      highlight.style.width = `${coords.width}px`;
      highlight.style.height = `${coords.height}px`;
      highlight.style.transform = `translate(${coords.left}px, ${coords.top}px)`;
    }
    triggers.forEach(a => a.addEventListener('mouseenter', highlightLink));
另外,聚光燈的 CSS 特效如下
.highlight {
  transition: all 0.2s;
  border-bottom: 2px solid white;
  position: absolute;
  top: 0;
  background: white;
  left: 0;
  z-index: -1;
  border-radius: 20px;
  display: block;
  box-shadow: 0 0 10px rgba(0,0,0,0.2);
}
以上是第二十二天的製作紀錄,如有錯誤或不足的地方還請多多指教 >.<
JavaScript Exercise: Follow Along Links - #JavaScript30 22/30
[ Alex 宅幹嘛 ] 深入淺出 Javascript30 快速導覽 | Day 22:Follow Along Link Highliter
MDN Web Docs